package com.blb.educourseservice.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.blb.common.entity.Course;
import com.blb.educourseservice.config.RabbitMQConfig;
import com.blb.educourseservice.service.ICourseService;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.UUID;

/**
 * 事件监听器
 */
@CanalEventListener
public class CanalListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ICourseService courseService;

    /**
     * 监听 edu_course数据库的course表
     */
    @ListenPoint(schema = "edu_course",table = "course")
    public void handleCourseUpdate(CanalEntry.EventType eventType, CanalEntry.RowData rowData){
        //判断操作的类型
        if("DELETE".equals(eventType.name())){
            //遍历删除前数据行的每一列
            rowData.getBeforeColumnsList().forEach(column -> {
                //获得删除前的ID
                if("id".equals(column.getName())){
                    //发删除消息给处理删除的队列
                    rabbitTemplate.convertAndSend(RabbitMQConfig.COURSE_EXCHANGE,
                            RabbitMQConfig.KEY_COURSE_REMOVE,
                            Long.valueOf(column.getValue()),
                            new CorrelationData(UUID.randomUUID().toString()));
                    return;
                }
            });
        }else if("INSERT".equals(eventType.name()) || "UPDATE".equals(eventType.name())){
            //获得插入或更新后的数据
            rowData.getAfterColumnsList().forEach(column -> {
                if("id".equals(column.getName())){
                    //通过id查询课程的完整信息
                    Course course = courseService.getCourseById(Long.valueOf(column.getValue()));
                    //包装到Course对象中，转换为JSON
                    String json = JSON.toJSONString(course);
                    //发送给添加或更新队列
                    rabbitTemplate.convertAndSend(RabbitMQConfig.COURSE_EXCHANGE,
                            RabbitMQConfig.KEY_COURSE_SAVE,
                            json,
                            new CorrelationData(UUID.randomUUID().toString()));
                }
            });
        }
    }
}
